package com.itxiuyixiu.volunteer.service;

import com.itxiuyixiu.entity.mapper.AdminReaderMapper;
import com.itxiuyixiu.entity.model.Admin;
import com.itxiuyixiu.tools.security.user.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author 黄磊
 * @date 2020/5/1
 */
@Service
public class AdminDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private AdminReaderMapper adminReaderMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminByUsername(username);
        if (!adminOptional.isPresent()) {
            throw new UserNotFoundException("没有找到用户：" + username);
        }
        Admin admin = adminOptional.get();
        return new User(admin.getUsername(), admin.getPassword(), admin.isEnabled(), true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList(admin.getAuthorities()));
    }
}
